package com.martini.satoken01.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.martini.satoken01.anno.AccessLimited;
import com.martini.satoken01.entity.Comment;
import com.martini.satoken01.model.AjaxJson;
import com.martini.satoken01.repository.CommentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author martini at 2021/12/17 15:59
 */
@Slf4j
@RequestMapping("/search")
@RestController
public class SearchController {

    private final CommentRepository commentRepository;

    public SearchController(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    /**
     * 搜索接口需要登陆
     *
     * @param params 搜索条件
     * @return 响应数据
     */
    @PostMapping
    @SaCheckLogin
    @AccessLimited(limitTimes = 5, limitDuration = 1000 * 60,
            limitInjectRemainTimesAttr = "remainTimes",
            limitInjectNextPermissionTimeAttr = "waitTime")
    public AjaxJson handleSearch(@RequestBody Map<String, String> params,
                                 @RequestParam(required = false) Integer remainTimes,
                                 @RequestParam(required = false) Long waitTime) {
        String text = params.get("text");
        log.info("Search Text: {}", text);
        Example<Comment> commentExample = Example.of(
                new Comment().setUsername(text),
                ExampleMatcher.matching()
                        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
        );
        List<Comment> comments = commentRepository.findAll(commentExample);
        try {
            Thread.sleep(1000 + Math.abs(new Random().nextLong()) % 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Map<String, Object> data = new HashMap<>(3);
        data.put("comments", comments);
        data.put("remainTimes", remainTimes);
        data.put("waitTime", waitTime);
        return AjaxJson.success().setData(data);
    }

}
